package com.qiyuesuo.service.imp;

import com.alibaba.fastjson.JSON;
import com.qiyuesuo.entity.Person;
import com.qiyuesuo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void registry(Person person) {
        String prefix = USER_PREFIX + "_" + person.getUsername();
        if (stringRedisTemplate.opsForValue().get(prefix) != null) throw new RuntimeException("用户存在");

        stringRedisTemplate.opsForValue().set(prefix, JSON.toJSONString(person));
    }

    @Override
    public String login(Person person) {
        String prefix = USER_PREFIX + "_" + person.getUsername();
        Person result = JSON.parseObject(stringRedisTemplate.opsForValue().get(prefix), Person.class);
        if (result != null && result.getPassword().equals(person.getPassword())) {
            String uuid = UUID.randomUUID().toString();
            stringRedisTemplate.opsForValue().set(USER_PREFIX + "_" + person.getUsername() + "_UUID", uuid);
            return uuid;
        }
        return "FAIL";
    }
}
